// store/main.js
import { createStore } from 'vuex';
import { get } from "@/net/index.js";
import axios from "axios";

export default createStore({
  state: {
    user: {
      id: -1,
      username: "",
      email: "",
      date: "",
      avatar: ""
    },
    forum: {
      types: []
    }
  },
  getters: {
    avatarGet(state) {
      if (state.user.avatar) {
        return `${axios.defaults.baseURL}/images/${state.user.avatar}`;
      }
      return "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png";
    },
    fetchForum(state, id) {
      for (let type of state.forum.types) {
        if (type.id === id) {
          return type;
        }
      }
    }
  },
  mutations: {
    setUser(state, user) {
      state.user = user;
    }
  },
  actions: {
    async fetchUser({ commit }) {
      try {
        const response = await new Promise((resolve, reject) => {
          get('api/user/info', (data) => {
            resolve(data);
          }, (error) => {
            reject(error);
          });
        });
        console.log("在赋值了");
        commit('setUser', response);
      } catch (error) {
        console.error("Failed to fetch user:", error);
        throw error;
      }
    }
  }
});
